/*
Copyright (c)2009 Seesmic, Inc

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package com.seesmic.twhix.xep.publish_subscribe
{
	import com.seesmic.twhix.IdHandler;
	import com.seesmic.twhix.MessageStanza;
	import com.seesmic.twhix.XPathHandler;
	import com.seesmic.twhix.xep.Plugin;
	
	
	public class PublishSubscribe extends Plugin
	{
		
		public function PublishSubscribe()
		{
			super();
			this.name = "Publish-Subscribe (XEP-0060)";
			this.shortcut = "pubsub";
		}
		
		public override function init():void {
			trace("Loaded Publish-Subscribe Plugin");
			xmpp.addHandler(new XPathHandler("{jabber:client}message/{http://jabber.org/protocol/pubsub#event}event/{http://jabber.org/protocol/pubsub#event}items/{http://jabber.org/protocol/pubsub#event}item", itemEventHandler));
			xmpp.addHandler(new XPathHandler("{jabber:client}message/{http://jabber.org/protocol/pubsub#event}event/{http://jabber.org/protocol/pubsub#event}items/{http://jabber.org/protocol/pubsub#event}retract", retractEventHandler));
		}
		
		private function itemEventHandler(message:MessageStanza):void {
			dispatchEvent(new PubSubEvent(PubSubEvent.ITEM, false, false, message));
			trace("Publish-Subscribe Item Event");
		}
		
		private function retractEventHandler(message:MessageStanza):void {
			dispatchEvent(new PubSubEvent(PubSubEvent.RETRACT, false, false, message));
			trace("Publish-Subscribe Retract Event");
		}

		public function getItems(jid:String, node:String, callback:Function):void {
			var id:String = this.xmpp.newId();
			var out:XML = <iq type='get' xmlns='jabber:client' to={jid} id={id}><pubsub xmlns='http://jabber.org/protocol/pubsub'><items node={node} /></pubsub></iq>;
			this.xmpp.addHandler(new IdHandler(id, callback));
			this.xmpp.send(out.toXMLString());
		}
		
	}
}
